var GLB = require("Glb");
var engine = require("MatchvsEngine");
var msg = require("MatvhsMessage");
var response = require("MatchvsResponse");
var userInfo;

cc.Class({
    extends: cc.Component,

    properties: {
        labelinfo:cc.Label,
        StartBtn:cc.Node
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.labelinfo.string = "aaaaa";
        var self = this;
        this.initEvent(self);
        this.StartBtn.on(cc.Node.EventType.TOUCH_END,function (event) {
            engine.prototype.init(GLB.channel,GLB.platform,GLB.gameID);
            GLB.platform = 'alpha';
        });
    },
    /**
     * 注册对应的事件监听和把自己的原型传递进入，用于发送事件使用
     */
    initEvent:function (self) {
        response.prototype.init(self);
        this.node.on(msg.MATCHVS_RE_CONNECT,this.onEvent,this);
        this.node.on(msg.MATCHVS_ERROE_MSG, this.onEvent, this);
        this.node.on(msg.MATCHVS_INIT, this.onEvent, this);
        this.node.on(msg.MATCHVS_REGISTER_USER,this.onEvent,this);
        this.node.on(msg.MATCHVS_LOGIN,this.onEvent,this);
        this.node.on(msg.MATCHVS_WX_BINDING,this.onEvent,this);
        this.node.on(msg.MATCHVS_ROOM_DETAIL,this.onEvent,this);
    },
    
    /**
     * 事件接收方法
     * @param event
     */
    onEvent:function (event) {
        switch (event.type){
            case msg.MATCHVS_INIT:
            this.labelinfo.string = "初始化成功";
                this.getUserFromWeChat(this);
                break;
            case msg.MATCHVS_REGISTER_USER:
                this.userInfo = event.detail.msg;
                console.log("event 注册成功:"+this.userInfo);
                this.login(this.userInfo.id,this.userInfo.token);
                break;
            case msg.MATCHVS_LOGIN:
                console.log("event 登录成功:"+this.userInfo);
                var MsLoginRsp = event.detail.MsLoginRsp;
                if (MsLoginRsp.roomID != null && MsLoginRsp.roomID !== '0') {
                    console.log("开始重连"+ MsLoginRsp.roomID);
                    engine.prototype.reconnect();
                } else {
                    // cc.director.loadScene("lobby");
                }
                break;
            case msg.MATCHVS_RE_CONNECT:
                // var reConnect  = event.detail.roomUserInfoList;
                // engine.prototype.getRoomDetail(reConnect.roomID);
                // GLB.roomID = reConnect.roomID;
                break;
            case msg.MATCHVS_ERROE_MSG:
                this.labelLog("[Err]errCode:"+event.detail.errorCode+" errMsg:"+event.detail.errorMsg);
                break;
            case msg.MATCHVS_WX_BINDING:
                console.log("event 微信绑定:"+this.userInfo);
                engine.prototype.login(event.detail.val.userid,event.detail.val.token);
                break;
            case msg.MATCHVS_ROOM_DETAIL:
                console.log("event 房间信息:"+this.userInfo);
                if (event.detail.rsp.state == 1) {
                    cc.director.loadScene('createRoom');
                } else {
                    cc.director.loadScene("game");
                }
                if (event.detail.rsp.owner == GLB.userID) {
                    GLB.isRoomOwner = true;
                } else {
                    GLB.isRoomOwner = false;
                }
                break;
        }
    },


    //------------------------微信流程----------------------------------------
    // 获取微信信息
    getUserFromWeChat:function(self){
        //获取微信信息
        try {
            //-----------使用wxshare.js提供的方法----------------------
            getWxUserInfo(function(userInfos){
                getUserOpenID(function (openInfos) {
                    userInfos.openInfos = openInfos;
                    self.bindOpenIDWithUserID(userInfos);
                });
            });
        } catch (error) {
            console.log("不是在微信平台，调用不进行绑定！");
            engine.prototype.registerUser();
        }
    },



    /**
     * 绑定微信OpenID 返回用户信息
     */
    bindOpenIDWithUserID:function(wxUserInfo){
        var self = this;
        console.log("获取到的微信用户信息",wxUserInfo);
        if(!wxUserInfo){
            return;
        }
        console.log("test2");
        if (wxUserInfo.openInfos.data == undefined) {
            console.warn("没有获取到微信OpenID，获取OpenID请参考："+'http://www.matchvs.com/service?page=third');
            engine.prototype.registerUser();
            return;
        }
        GLB.isWX = true;
        var req = new  XMLHttpRequest();
        let reqUrl = this.getBindOpenIDAddr(GLB.channel,GLB.platform);
        console.log("req post 1"+reqUrl);
        req.open("post",reqUrl , true);
        console.log("req post 1 -2");
        req.setRequestHeader("Content-Type", "application/json")
        console.log("req post 1 -3");
        req.onreadystatechange = function () {
            console.log("req post 2");
            if (req.readyState == 4 && (req.status >= 200 && req.status < 400)) {
                try{
                    console.log("req post 3");
                    var response = req.responseText;
                    var data = JSON.parse(response).data;
                    console.log(data.userid,data.token);
                    console.log("req post 4");
                    self.login(data.userid,data.token);
                    console.log("req post 5");
                } catch(error){
                    console.warn(error.message);
                    console.log("req post 6");
                    engine.prototype.registerUser();

                    console.log("req post 7");
                    let userNameLabel = cc.find('NameLabel').getComponent(cc.Label);
                    userNameLabel.string = wxUserInfo.nickName;

                    console.log("req post 8");

                    GLB.name = wxUserInfo.nickName;
                    GLB.avatar = wxUserInfo.avatarUrl;
                    // console.log("下载头像图片地址222:"+wxUserInfo.avatarUrl);
                    let png = cc.find('HeadIcon').getComponent(cc.Sprite);
                    let image = wx.createImage();
                    image.onload = () => {
                        try {
                            console.log("req post 9");
                            let texture = new cc.Texture2D();
                            texture.initWithElement(image);
                            texture.handleLoadedTexture();
                            png.spriteFrame = new cc.SpriteFrame(texture);
                            console.log("req post 10");
                        } catch (e) {
                            console.log('wx onload image error');
                        }
                    }
                    image.src = GLB.avatar;

                    console.log("req post 11");
                    // cc.loader.load(iconUrl+"?aaa=aa.jpg", function (err, res) {
                    //     if (err) {
                    //         console.error('load avatar image error', err);
                    //         return;
                    //     }
            

                    //     let png = cc.find('HeadIcon').getComponent(cc.Sprite);
                    //     png.spriteFrame = new cc.SpriteFrame(res);
                    // })
                }
            }
        };
        //sign=md5(appKey&gameID=value1&openID=value2&session=value3&thirdFlag=value4&appSecret)
        let params = "gameID="+GLB.gameID+"&openID="+wxUserInfo.openInfos.data.openid+"&session="+wxUserInfo.openInfos.data.session_key+"&thirdFlag=1";
        //计算签名
        let signstr = this.getSign(params);
        //重组参数
        params = "userID=0&"+params+"&sign="+signstr;

        let jsonParam ={
            userID:0,
            gameID:GLB.gameID,
            openID:wxUserInfo.openInfos.data.openid,
            session:wxUserInfo.openInfos.data.session_key,
            thirdFlag:1,
            sign:signstr
        };
        req.send(jsonParam);

        console.log("test8");


    },

    getBindOpenIDAddr :function(channel, platform){
        if(channel == "MatchVS" || channel == "Matchvs"){
            if(platform == "release"){
                return "http://vsuser.matchvs.com/wc6/thirdBind.do?"
            }else if(platform == "alpha"){
                return "http://alphavsuser.matchvs.com/wc6/thirdBind.do?";
            }
        }else if(channel == "MatchVS-Test1"){
            if(platform == "release"){
                return "http://zwuser.matchvs.com/wc6/thirdBind.do?"
            }else if(platform == "alpha"){
                return "http://alphazwuser.matchvs.com/wc6/thirdBind.do?";
            }
        }
    },

    getSign:function(params){
        let str = GLB.appKey+"&"+params+"&"+GLB.secret;
        console.log(str);
        let md5Str = hex_md5(str);
        console.log(md5Str);
        return md5Str;
    },

    //------------------------微信流程----------------------------------------
    //------------------------登录服务器----------------------------------------
    /**
     * 登录
     * @param id
     * @param token
     */
    login: function (id, token) {
        GLB.userID = id;
        console.log('开始登录...用户ID:' + id + " gameID " + GLB.gameID);
        engine.prototype.login(id,token);
    },
});
